package com.usefullc.chatgpt.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author: Sampson
 * @date: 6/26/23 10:32 AM
 */
public class IndexController {

    public static void main(String[] args) throws IOException {
        String url = "";
        String cookie = "";
        String uploadData=  "{\"action\":\"next\",\"messages\":[{\"id\":\"aaa2c1ec-73a4-4d9d-a53a-47b61ea7a369\",\"author\":{\"role\":\"user\"},\"content\":{\"content_type\":\"text\",\"parts\":[\"用java 写个event-stream示例 直接用HttpURLConnection\"]},\"metadata\":{}}],\"parent_message_id\":\"aaa13523-98eb-4b96-9762-5f1b0fac4ab6\",\"model\":\"text-davinci-002-render-sha\",\"timezone_offset_min\":-480,\"history_and_training_disabled\":false,\"arkose_token\":null}";
        HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        urlConnection.setRequestProperty("Connection", "Keep-Alive");
        urlConnection.setRequestProperty("Charset", "UTF-8");
        urlConnection.setRequestProperty("Cookie", cookie );
        urlConnection.setRequestProperty("Accept", "text/event-stream");
        urlConnection.getOutputStream().write(JSON.toJSONString(uploadData).getBytes(StandardCharsets.UTF_8));
        InputStream inputStream = urlConnection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line = bufferedReader.readLine();
        while(StringUtils.isNotEmpty(line)){
            System.out.printf("line="+line);
        }
    }



}
